package com.ruoyi.position.utils;

import cn.hutool.json.JSONUtil;
import com.ruoyi.position.domin.dto.DisTrackMessageDTO;
import com.ruoyi.position.domin.entity.DisTrack;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 马兰友
 * @Date: 2024/04/01/20:01
 */
public class EarthquakeUtil {

    public static List<DisTrack> getData() throws Exception {
        String host = "https://earlywarn.market.alicloudapi.com";
        String path = "/api/warning/earthquake_data";
        String method = "GET";
        String appcode = "c1624c8a9cf44ddeb1daf7809f1696e9";
        Map<String, String> headers = new HashMap<>();

        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        querys.put("pubtime_end", now.format(formatter));
        querys.put("time_limit", "24");
        querys.put("time_unit", "hour");

        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        String body = EntityUtils.toString(response.getEntity());
        StringBuilder sb = new StringBuilder(body);

        int index;
        while ((index = sb.indexOf("震级")) != -1) {
            sb.replace(index, index + 2, "level");
        }
        while ((index = sb.indexOf("位置")) != -1) {
            sb.replace(index, index + 2, "location");
        }
        while ((index = sb.indexOf("经度")) != -1) {
            sb.replace(index, index + 2, "lng");
        }
        while ((index = sb.indexOf("纬度")) != -1) {
            sb.replace(index, index + 2, "lat");
        }
        while ((index = sb.indexOf("深度")) != -1) {
            sb.replace(index, index + 2, "depth");
        }
        while ((index = sb.indexOf("发布时间")) != -1) {
            sb.replace(index, index + 4, "createTime");
        }
        DisTrackMessageDTO bean = JSONUtil.toBean(sb.toString(), DisTrackMessageDTO.class);

        return JSONUtil.toList(bean.getData(), DisTrack.class);
    }


}
